const { DefinePlugin } = require("webpack");
const chalk = require("chalk");
const ProgressBarPlugin = require("progress-bar-webpack-plugin");
const hasha = require('hasha');
const path = require('path')
const resolveApp = require("./paths");


// 导入抽取css的插件
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const generateScopedName = (name, filename) => {
  console.log('getLocalIdent', name, filename);

  const hash = hasha(filename + name, { algorithm: 'md5' });

  let basename = ''
  if (filename.endsWith('.css')) {
    basename = path.basename(filename, '.css');
  } else {
    basename = path.basename(filename, '.less');
  }

  return `${basename}-${name}-${hash.slice(0, 5)}`;
};
module.exports = {
  entry: {
    app: ["./src/index.js"], // 相对路径（相对 context）
  },
  // context: '', 项目根目录

  module: {
    rules: [
      {
        test: /.css$/,
        use: [
          process.env.NODE_ENV === 'production' ? MiniCssExtractPlugin.loader : 'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,  // 向前找一个，在用 postcss 处理一次
              sourceMap: true,
              modules: {
                // localIdentName: '[name]__[local]-[hash:base64:5]'
                getLocalIdent({ resourcePath }, localIdentName, localName) {
                  return generateScopedName(localName, resourcePath);
                }
              }
            }
          },
          'postcss-loader'
        ],
      },
      {
        test: /.less$/,
        use: [
          process.env.NODE_ENV === 'production' ? MiniCssExtractPlugin.loader : 'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 2,  // 向前找一个，在用 postcss 处理一次
              sourceMap: true,
              modules: {
                // localIdentName: '[name]__[local]-[hash:base64:5]'
                getLocalIdent({ resourcePath }, localIdentName, localName) {
                  return generateScopedName(localName, resourcePath);
                }
              }
            }
          },
          'less-loader',
          'postcss-loader'
        ],
      },
      {
        test: /.(png|jpe?g|svg|gif)$/,
        type: 'asset', // 使用 webpack5 解析图片资源
        generator: {
          filename: "images/[name].[hash:4][ext]"
        },
        parser: {
          dataUrlCondition: {
            maxSize: 25 * 1024  // 大于 25k 直接打复制到 dist/img 目录中(file-loader)，小于 25k 内置到 index.html(url-loader)
          }
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, // 加载视频资源
        type: 'asset', // 使用 webpack5 解析图片资源
        generator: {
          filename: "images/[name].[hash:4][ext]"
        },
        parser: {
          dataUrlCondition: {
            maxSize: 244 * 1024  // 大于 25k 直接打复制到 dist/img 目录中(file-loader)，小于 25k 内置到 index.html(url-loader)
          }
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/i, // 加载字体资源
        type: 'asset/resource',
        generator: {
          filename: "font/[name].[hash:4][ext]"
        },
      },
      {
        test: /(\.jsx|\.js)$/,
        use: ["babel-loader"],
        exclude: /node_modules/,
      },
      {
        test: /.html$/,
        use: ["html-loader"],
      }
    ],
  },
  plugins: [
    // new htmlWebpackPlugin({
    //   title: "webpack 搭建项目",
    //   template: "./public/index.html",
    //   minify: {
    //     collapseWhitespace: process.env.NODE_ENV === 'production' ? true : false, //合并多余的空格
    //     removeComments: process.env.NODE_ENV === 'production' ? true : false, //移除注释
    //     removeAttributeQuotes: process.env.NODE_ENV === 'production' ? true : false, //移除属性上的双引号
    //   }
    // }),
    new DefinePlugin({
      // 为 index.html 传递常量参数
      BASE_URL: process.env.NODE_ENV === 'production' ? "./public/" : "./",

    }),
    new ProgressBarPlugin({ // 使用进度条显示构建进度
      format: ` :msg [:bar] ${chalk.green.bold(':percent')} (:elapsed s)`
    })
  ],
  resolve: {
    extensions: [".js", ".jsx", ".json"], // 省略文件后缀
    alias: { // 配置别名
      // "@": path.resolve(__dirname, "./src"),
      "@": resolveApp('./src')
    },
  },
};
